import 'package:carousel_slider/carousel_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/extension/ex_widget.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/common_lib/ui/common_component.dart';
import 'package:flutter_massage/generated/assets.dart';
import 'package:flutter_massage/pages/home/home_component.dart';
import 'package:flutter_massage/pages/login/index.dart';
import 'package:flutter_massage/pages/main/main_logic.dart';
import 'package:flutter_massage/pages/message/message_bean.dart';
import 'package:flutter_massage/pages/message/message_detail_page.dart';
import 'package:flutter_massage/pages/message/message_logic.dart';
import 'package:flutter_massage/pages/message/message_utils.dart';
import 'package:flutter_massage/pages/model/bean.dart';
import 'package:flutter_massage/pages/my/attention/my_attention_logic.dart';
import 'package:flutter_massage/pages/technician/place_order/place_order_page.dart';
import 'package:flutter_massage/pages/technician/report/report_page.dart';
import 'package:flutter_massage/pages/technician/store_detail/store_detail_page.dart';
import 'package:flutter_massage/pages/technician/technician_detail/technician_detail_logic.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/sqlite/db_manager.dart';
import 'package:flutter_massage/values/colors.dart';
import 'package:flutter_massage/values/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class TechnicianDetailPage extends GetView<TechnicianDetailLogic> {
  const TechnicianDetailPage(this.bean, {super.key});

  final TechnicianBean bean;

  static const String keyListener = 'key_listener_set_black';

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      titleStr: '技师详情',
      scaffoldBackgroundColor: AppColors.grayF8,
      actions: [
        CommonRootAction(
          child: Assets.svgAppbarMore.toSvg(width: 20.w),
          onTap: () {
            ActionBottomSheet.popModal(
              safeBottom: false,
              safeAreaMinimum: EdgeInsets.fromLTRB(16.w, 0, 16.w, 28.w),
              child: Container(
                decoration: CommonDecoration.getShapeDecoration(radius: 16.w, bg: AppColors.white),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        _buildBtn('举报', Assets.svgReport, () => CommonRoute.open(const ReportPage())),
                        CommonMargin.width(73.w),
                        _buildBtn(
                          '拉黑',
                          Assets.svgBlackList,
                          () {
                            CommonDialog.cupertinoTwoButton(
                              title: '确认要将该用户拉黑吗？',
                              description: '对方将无法查看您的信息，您也不会收到关于TA的推荐。对方不会收到被拉黑的通知。',
                              cancelTitle: '取消',
                              confirmTitle: '拉黑',
                              onConfirm: () async {
                                await GetStorageService.setBlack(bean.id);
                                CommonObservable().publishChange(keyListener);
                                CommonRoute.close();
                              },
                            );
                          },
                        ),
                      ],
                    ).paddingVertical(16.w),
                    const CommonDivider(),
                    ButtonWidget.text(
                      '取消',
                      onTap: () => CommonRoute.close(),
                      hasInkWell: false,
                      height: 50.w,
                      alignment: Alignment.center,
                      textColor: '#CCCCCC'.toColor,
                      fontSize: 16,
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ],
      child: GetBuilder<TechnicianDetailLogic>(
        init: TechnicianDetailLogic(),
        assignId: true,
        builder: (logic) {
          return SingleChildScrollView(
            padding: EdgeInsets.all(12.w),
            child: Column(
              children: [
                TechnicianDetailTopInfo(bean),
                TechnicianDetailPictures(bean).paddingTop(12.w),
                TechnicianDetailComment(bean).paddingTop(16.w),
                TechnicianDetailProject(bean).paddingTop(16.w),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildBtn(String title, String icon, VoidCallback onTap) {
    return ButtonWidget(
      hasInkWell: false,
      onTap: () {
        CommonRoute.close();
        onTap.call();
      },
      child: Column(
        children: [
          icon.toSvg(width: 70.w),
          TextWidget.oneLine(text: title, fontSize: 14, color: AppColors.textLevelThree).paddingTop(6.w),
        ],
      ),
    );
  }
}

class TechnicianDetailTopInfo extends StatelessWidget {
  const TechnicianDetailTopInfo(this.bean, {super.key});

  final TechnicianBean bean;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        ImageWidget.url(
          bean.header ?? '',
          width: 75.w,
          height: 75.w,
          radius: 75.w,
        ),
        CommonMargin.width(8.w),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                TextWidget.oneLine(
                  text: bean.name ?? '',
                  fontSize: 16,
                  color: AppColors.textLevelOne,
                  fontWeight: FontWeight.bold,
                ).expanded(),
                ButtonWidget.text(
                  '私信TA',
                  width: 50.w,
                  height: 21.w,
                  backgroundColor: AppColors.primaryOrange,
                  alignment: Alignment.center,
                  borderRadius: 4.w,
                  textColor: AppColors.white,
                  fontSize: 12,
                  hasInkWell: false,
                  onTap: () async {
                    if (bean.id == null) return;
                    ChatBean chatBean = ChatBean(
                      chatId: MessageUtils.createChatId(bean.id!.toString()),
                      name: bean.name,
                      avatar: bean.header,
                      message: '',
                      updateTime: DateTime.now().millisecondsSinceEpoch.toString(),
                      userId: MessageUtils.userKey,
                    );
                    await DbManager.updateChat(bean: chatBean);
                    if (chatBean.chatId.empty) return;
                    CommonRoute.open(MessageDetailPage(chatId: chatBean.chatId!, name: chatBean.name ?? ''));
                    CommonObservable().publishChange(MessageLogic.keyListener);
                  },
                ),
              ],
            ),
            CommonMargin.height(8.w),
            Row(
              children: [
                Row(
                  children: [
                    Text.rich(
                      TextSpan(
                        text: '评分：',
                        children: [
                          TextSpan(text: bean.score ?? '', style: const TextStyle(color: AppColors.primaryOrange)),
                        ],
                        style: TextStyle(fontSize: 12, color: '#66737F'.toColor, fontWeight: FontWeight.bold),
                      ),
                    ),
                    CommonMargin.width(24.w),
                    Text.rich(
                      TextSpan(
                        text: '已服务人次：',
                        children: [
                          TextSpan(
                            text: (bean.servedNum ?? 0).toString(),
                            style: const TextStyle(color: AppColors.primaryOrange),
                          ),
                        ],
                        style: TextStyle(fontSize: 12, color: '#66737F'.toColor, fontWeight: FontWeight.bold),
                      ),
                    ).flexible(),
                  ],
                ).expanded(),
                GetBuilder<TechnicianDetailLogic>(
                  builder: (logic) {
                    bool attention = GetStorageService.isAttentionTechnician(bean.id);
                    return ButtonWidget.text(
                      attention ? '取消关注' : '关注',
                      width: 48.w,
                      height: 19.w,
                      alignment: Alignment.center,
                      borderRadius: 4.w,
                      textColor: AppColors.primaryGreen,
                      fontSize: 12,
                      borderColor: AppColors.primaryGreen,
                      borderWidth: 1,
                      onTap: () {
                        GetStorageService.setAttentionTechnician(bean.id);
                        logic.update();
                        CommonObservable().publishChange(MyAttentionLogic.keyListener);
                      },
                      hasInkWell: false,
                    );
                  },
                ),
              ],
            ),
            Row(
              children: [
                ButtonWidget.textIcon(
                  bean.shop?.shopName ?? '',
                  Assets.svgArrowRightGray.toSvg(width: 8.w, color: '#66737F'.toColor),
                  fontSize: 12,
                  textColor: '#66737F'.toColor,
                  fontWeight: FontWeight.bold,
                  spacing: 4.w,
                  hasInkWell: false,
                  onTap: () async {
                    Shop? temp = JsonService.getShopById(bean.shop?.shopId);
                    if (temp == null) return;
                    CommonRoute.open(StoreDetailPage(temp));
                  },
                ).expanded(),
                ButtonWidget.iconText(
                  Assets.svgLocationGreen.toSvg(width: 13.w),
                  bean.distance ?? '',
                  fontSize: 13,
                  textColor: AppColors.primaryGreen,
                  spacing: 2.w,
                  hasInkWell: false,
                ),
              ],
            ).paddingTop(8.w),
          ],
        ).expanded(),
      ],
    ).card(padding: EdgeInsets.all(12.w), radius: 8.w);
  }
}

class TechnicianDetailPictures extends StatelessWidget {
  TechnicianDetailPictures(this.bean, {super.key});

  final TechnicianBean bean;

  final ValueNotifier<int> currentIndex = ValueNotifier(0);

  final CarouselController carouselController = CarouselController();

  @override
  Widget build(BuildContext context) {
    List<String> album = bean.album ?? [];
    return ValueListenableBuilder(
      valueListenable: currentIndex,
      builder: (BuildContext context, int value, Widget? child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CarouselWidget(
              items: album,
              boxFit: BoxFit.cover,
              aspectRatio: 1,
              showIndicator: false,
              onPageChanged: (index, _) => currentIndex.value = index,
              carouselController: carouselController,
            ),
            ListView.separated(
              scrollDirection: Axis.horizontal,
              itemCount: album.length,
              itemBuilder: (BuildContext context, int index) {
                Widget child = index == value
                    ? Container(
                        decoration: CommonDecoration.getShapeDecoration(
                          radius: 4.w,
                          borderWidth: 2.w,
                          borderColor: AppColors.primaryGreen,
                        ),
                      )
                    : Container(color: Colors.white.withOpacity(0.7));
                return ButtonWidget(
                  onTap: () {
                    currentIndex.value = index;
                    carouselController.animateToPage(index);
                  },
                  hasInkWell: false,
                  child: AspectRatio(
                    aspectRatio: 1,
                    child: Stack(
                      children: [
                        ImageWidget.url(
                          album[index],
                          radius: 4.w,
                        ).positioned(left: 0, right: 0, top: 0, bottom: 0),
                        child,
                      ],
                    ),
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) => CommonMargin.width(4.w),
            ).height(67.w).paddingTop(5.w),
            TextWidget.moreLine(
              text: bean.info ?? '',
              fontSize: 12,
              color: '#66737F'.toColor,
              fontWeight: FontWeight.bold,
            ).paddingTop(8.w),
          ],
        );
      },
    );
  }
}

class TechnicianDetailComment extends StatelessWidget {
  const TechnicianDetailComment(this.bean, {super.key});

  final TechnicianBean bean;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const CommonTitleComponent(title: '对TA的评价'),
        LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            double spacing = 5.w;
            double width = ((constraints.maxWidth - spacing * 3 - 4 * 2) / 4).floorToDouble();
            return Wrap(
              spacing: spacing,
              runSpacing: spacing,
              children: (bean.commentLabels ?? []).map((e) {
                return ButtonWidget.text(
                  e,
                  width: width,
                  height: 30.w,
                  alignment: Alignment.center,
                  borderRadius: 4.w,
                  textColor: AppColors.primaryGreen,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                  borderColor: AppColors.primaryGreen,
                  borderWidth: 1,
                );
              }).toList(),
            );
          },
        ).paddingTop(12.w),
      ],
    );
  }
}

class TechnicianDetailProject extends StatelessWidget {
  const TechnicianDetailProject(this.bean, {super.key});

  final TechnicianBean bean;

  @override
  Widget build(BuildContext context) {
    List<ProjectBean> result = bean.serviceItems ?? [];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const CommonTitleComponent(title: '服务项目'),
        Column(
          children: List.generate(
              result.length,
              (index) => HomeRecommendProject(result[index], onTapOrder: () async {
                    String key = Storage().getString(StorageKey.userKey);
                    if (key.empty) {
                      CommonRoute.open(const LoginPage(hideBackBtn: false));
                      return;
                    }
                    // SettingBean settingBean = await XydUserService.getCacheMineInfoBean();
                    // if (settingBean.full.empty) {
                    if (bean.id == null || result[index].itemId == null) return;
                    CommonRoute.open(PlaceOrderPage(
                      technicianId: bean.id!,
                      projectId: result[index].itemId!,
                    ));
                    // } else {
                    //   String text = settingBean.full!;
                    //   CommonDialog.twoButton(
                    //     title: '温馨提示',
                    //     description: text,
                    //     cancelTitle: '取消',
                    //     confirmTitle: '好的',
                    //     onConfirm: () {
                    //       MainLogic logic = Get.find<MainLogic>();
                    //       logic.onJumpToPage(MainLogic.tabTc);
                    //       CommonRoute.close();
                    //     },
                    //   );
                    // }
                  }).paddingBottom(12.w)),
        ).paddingTop(12.w),
      ],
    );
  }
}
